<?php
namespace Home\Controller;
use Think\Controller;

// 后台用户模块
class UserController extends CommonController {
	function _filter(&$map){
		$map['status'] = array('gt', 0);
		if(!$_SESSION['administrator']){
			$map['id'] = array('egt',2);
			if(!empty($_POST['account'])) {
				$map['account'] = array('like',"%".$_POST['account']."%");
			}
		}
	}

	// 检查帐号
	public function checkAccount() {
		if(!preg_match('/^[a-z]\w{4,}$/i',$_POST['account'])) {
			$this->error( '用户名必须是字母，且5位以上！');
		}
		$User = M("User");
		// 检测用户名是否冲突
		$name = $_REQUEST['account'];
		$result = $User->getByAccount($name);
		if($result) {
			$this->error('该用户名已经存在！');
		}else {
			$this->success('该用户名可以使用！');
		}
	}

	public function add(){
		$this->assign('data', M('Role')->select());
		$this->display();
	}

	public function _before_edit(){
		$this->assign('data', M('Role')->select());
		$this->assign('roleId', M('RoleUser')->where('user_id='.$_REQUEST['id'])->getField('role_id'));
	}

	// 插入数据
	public function insert() {
		// 创建数据对象
		$User = D("User");
		if(!$User->create()) {
			$this->error($User->getError());
		}else{
			// 写入帐号数据
			if($result = $User->add()) {
				$this->addRole($result, $_POST['roleId']);
				$this->success('用户添加成功！');
			}else{
				$this->error('用户添加失败！');
			}
		}
	}

	protected function addRole($userId, $role_id = 0) {
		if($role_id){
			//新增用户自动加入相应权限组
			$RoleUser = M("RoleUser");
			$RoleUser->where('user_id='.$userId)->delete();
			// 默认加入网站编辑组
			$RoleUser->role_id = $role_id;
			$RoleUser->user_id = $userId;
			$RoleUser->add();
		}
	}

	//重置密码
	public function resetPwd() {
		$id = $_POST['id'];
		$password = $_POST['password'];
		if(''== trim($password)) {
			$this->error('密码不能为空！');
		}
		$User = M('User');
		$User->password	= md5($password);
		$User->id =	$id;
		$result	= $User->save();
		if(false !== $result) {
			$this->success("密码修改为$password");
		}else {
			$this->error('重置密码失败！');
		}
	}

	public function _after_update(){
		$this->addRole($_POST['id'], $_POST['roleId']);
	}
}